package com.chunxuan.langquan.ui.activity;

import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chunxuan.langquan.R;
import com.chunxuan.langquan.base.Base2Activity;
import com.chunxuan.langquan.base.BaseResult2;
import com.chunxuan.langquan.base.Global;
import com.chunxuan.langquan.dao.bean.CourseDetail;
import com.chunxuan.langquan.dao.http.APIRetrofit2;
import com.chunxuan.langquan.support.util.GlideUtil;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.ScreenUtils;
import com.ruitu.arad.util.SizeUtils;
import com.ruitu.arad.util.ToastUtils;

import java.util.Arrays;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class CourseTeacherInfoActivity extends Base2Activity {
    private ImageView iv_header, iv_back;
    private TextView tv_teacher_name, tv_brief;// 教师姓名,简介
    private RecyclerView rcv_labels;// 教师标签
    private WebView webview;
    public final static String CSS_STYLE ="<style>* p {color:#72ECFB;}</style>";
    private LabeListAdapter labelAdapter;

    private String teacher_id;//
    private CourseDetail.TeacherInfo info;// 请求得到的教师信息

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_course_teacher_info;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        iv_back = findViewById(R.id.iv_back);
        iv_header = findViewById(R.id.iv_header);
        tv_teacher_name = findViewById(R.id.tv_teacher_name);
        tv_brief = findViewById(R.id.tv_brief);
        rcv_labels = findViewById(R.id.rcv_labels);
        webview = findViewById(R.id.webview);

        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            teacher_id = bundle.getString("teacher_id");
        }

//        setHeadTitle();

        reqTeacherInfo();
        showProgress();

        labelAdapter = new LabeListAdapter(this);
        GridLayoutManager manager = new GridLayoutManager(this, 4);
        rcv_labels.setLayoutManager(manager);
        rcv_labels.setAdapter(labelAdapter);

        setOnClickListener(iv_back);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == iv_back) {
            onBackPressed();
        }
    }

    private Disposable reqTeacherInfo() {
        return APIRetrofit2.getDefault().reqTeacherInfo(Global.HEADER, teacher_id)
                .compose(RxUtil.<BaseResult2<CourseDetail.TeacherInfo>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<CourseDetail.TeacherInfo>>() {
                    @Override
                    public void accept(BaseResult2<CourseDetail.TeacherInfo> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            info = result2.getData();
                            if (null != info) {
                                GlideUtil.loadImg(info.getTeacheravatar(), iv_header);
                                tv_teacher_name.setText(info.getName());
                                tv_brief.setText(info.getBrief_intro());

                                initWebview(info.getContent());

                                try {
                                    String labels = info.getTeacher_label();
                                    String[] labelArr = labels.split("\\|");
                                    List<String> labelList = Arrays.asList(labelArr);
                                    labelAdapter.setDataList(labelList);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                ToastUtils.showShort("教师信息错误");
                            }
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取教师详情失败");
                    }
                });
    }

    private void initWebview(String url) {
        // 开启js支持
        webview.getSettings().setJavaScriptEnabled(true);
        //2、关闭自动适应
        webview.getSettings().setUseWideViewPort(false);
        webview.getSettings().setLoadWithOverviewMode(false);
        // 3、//重写WebViewClient中的onPageFinished方法
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //修改图片大小
                int screenWidth = ScreenUtils.getScreenWidth();
//                String width = String.valueOf(screenWidth - SizeUtils.dp2px(50));
//                String width2 = String.valueOf(screenWidth - SizeUtils.dp2px(10));
                String width2 = String.valueOf(SizeUtils.px2dp(screenWidth) - 15);

                String javascript = "javascript:function ResizeImages() {" +
                        "var myimg,oldwidth;" +
                        "var maxwidth = document.body.clientWidth;" +
                        "for(i=0;i <document.images.length;i++){" +
                        "myimg = document.images[i];" +
//                        "myimg.margin = 0;" +
                        "if(myimg.width > " + width2 + "){" +
                        "oldwidth = myimg.width;" +
                        "myimg.width =" + width2 + ";" +
                        "}" +
                        "}" +
                        "}";
                view.loadUrl(javascript);
                view.loadUrl("javascript:ResizeImages();");
            }
        });
        webview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        webview.setBackgroundColor(0); // 设置背景色
//        webview.getBackground().setAlpha(0);
//        webview.loadUrl(url);
        webview.loadData(CSS_STYLE+url, "text/html;charset=utf-8", null); // 加载定义的代码，并设定编码格式和字符集。
    }

    private class LabeListAdapter extends ListBaseAdapter<String> {

        public LabeListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_teacher_info_label;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView tv_label = holder.getView(R.id.tv_label);
            tv_label.setText(mDataList.get(position));
        }
    }
}